﻿using System;
using System.Collections.Specialized;
using System.Configuration.Provider;

namespace MembershipAdapter
{
    public class RoleProviderSettings
    {
        private NameValueCollection config;

        public string AppName { get; set; }

        public int CommandTimeout { get; set; }

        public RoleProviderSettings(NameValueCollection config)
        {
            this.config = config;
        }

        public virtual NameValueCollection Initialize(bool throwOnError = true)
        {
            this.CommandTimeout = SecUtility.GetIntValue(config, "commandTimeout", 30, true, 0);
            this.AppName = config["applicationName"];
            if (string.IsNullOrEmpty(this.AppName))
            {
                this.AppName = SecUtility.GetDefaultAppName();
            }

            if (this.AppName.Length > 256)
            {
                throw new ProviderException(SR.GetString(SR.Provider_application_name_too_long));
            }

            if (throwOnError)
            {
                config.Remove("applicationName");
                config.Remove("commandTimeout");
                if (config.Count > 0)
                {
                    var attribUnrecognized = config.GetKey(0);
                    if (string.IsNullOrEmpty(attribUnrecognized) == false)
                    {
                        throw new ProviderException(SR.GetString(SR.Provider_unrecognized_attribute, attribUnrecognized));
                    }
                }
            }

            return this.config;
        }
    }
}